<template>
    <n-popover class="!p-0" trigger="manual" :show="shown" placement="bottom">
        <template #trigger>
            <hover-container
                tooltip-content="消息通知"
                :inverted="theme.header.inverted"
                class="relative w-40px h-full"
            >
                <div class="wh-full flex flex-center user_msg_tips" @click="show()">
                    <jb-icon icon="clarity:notification-line" class="text-18px"></jb-icon>
                    <span
                        v-if="tipShown"
                        class="text-20px font-bold absolute top-4px right-3px"
                        style="color: red"
                        >·</span
                    >
                    <n-badge
                        value=""
                        :max="99"
                        :class="[count < 10 ? '-right-2px' : '-right-10px']"
                        class="absolute top-10px"
                    />
                </div>
            </hover-container>
        </template>
        <n-tabs
            v-model:value="currentTab"
            :class="[isMobile ? 'w-276px' : 'w-360px', 'user_msg_tips']"
            type="line"
            justify-content="space-evenly"
        >
            <n-tab-pane v-for="(item, index) in tabData" :key="item.key" :name="index">
                <template #tab>
                    <div
                        class="flex-x-center items-center"
                        :class="[isMobile ? 'w-92px' : 'w-120px']"
                    >
                        <span class="mr-5px">{{ item.name }}</span>
                        <n-badge
                            v-bind="item.badgeProps"
                            :value="
                                item.list.filter((message: any) => !message.isRead).length
                            "
                            :max="99"
                            show-zero
                        />
                    </div>
                </template>
                <loading-empty-wrapper
                    :item="item"
                    class="h-360px"
                    :loading="loading"
                    :empty="item.list.length === 0"
                    :item-key="item.itemKey"
                    placeholder-class="bg-$n-color transition-background-color duration-300 ease-in-out"
                >
                    <message-list
                        :list="item.list"
                        :item-key="item.itemKey"
                        @read="loadData()"
                    />
                </loading-empty-wrapper>
            </n-tab-pane>
        </n-tabs>
        <div
            v-if="showAction"
            class="flex border-t border-$n-divider-color cursor-pointer"
        >
            <div
                class="flex-1 text-center py-10px border-l border-$n-divider-color"
                @click="handleLoadMore"
            >
                查看更多
            </div>
        </div>
    </n-popover>
</template>

<script lang="ts" setup>
import { computed, onMounted, ref, watch } from 'vue'

import { useRouter } from 'vue-router'
import { useAppStore, useThemeStore } from '@/store'
import { useBasicLayout } from '@/composables'
import { useBoolean } from '@/hooks'
import { JBoltApi } from '@/utils/request'
import { ResData } from '@/typings/request'
import { PageNames } from '@/router/routes/pagenames'
import MessageList from './message-list.vue'

defineOptions({ name: 'SystemMessage' })
const router = useRouter()
const theme = useThemeStore()
const { isMobile } = useBasicLayout()
const { bool: loading } = useBoolean()

const currentTab = ref(0)

const tabData = ref<App.MessageTab[]>([
    {
        key: 1,
        name: '通知',
        itemKey: 'sysNotice',
        badgeProps: { type: 'warning' },
        list: []
    },
    {
        key: 3,
        name: '待办',
        itemKey: 'todo',
        badgeProps: { type: 'info' },
        list: []
    }
])

const count = computed(() => {
    return tabData.value.reduce((acc: any, cur: any) => {
        return acc + cur.list.filter((item: any) => !item.isRead).length
    }, 0)
})

const showAction = computed(() => tabData.value[currentTab.value].list.length > 0)

function handleLoadMore() {
    router.push({ name: PageNames.USER_NOTICE })
}

const shown = ref<boolean>(false)
const appStore = useAppStore()
const tipShown = computed(() => appStore.messageTipShown)

function show() {
    useAppStore().setMessageTipShown(false)
    shown.value = true
    loadData()
}
async function loadData() {
    const { result: noticeList } = await JBoltApi.get<ResData>(
        '/api/admin/msgCenter/sysNoticePortalDatas'
    )
    const { result: todoList } = await JBoltApi.get<ResData>(
        '/api/admin/msgCenter/todoPortalDatas'
    )
    noticeList.data.forEach((item: any) => {
        item.tagTitle = item.priorityLevelName
    })
    tabData.value[0].list = noticeList.data
    tabData.value[1].list = todoList.data
}

onMounted(async () => {
    await loadData()

    if (tabData.value[0].list?.length || tabData.value[1].list?.length) {
        useAppStore().setMessageTipShown(true)
    }

    document.addEventListener('click', function (e) {
        if (!shown.value) {
            return
        }
        //被点击的元素或者其子元素是否包含user_msg_tips类名，如果不包含就关掉
        if (!(e.target as HTMLElement).closest('.user_msg_tips')) {
            shown.value = false
        }
    })
})
</script>
<style scoped></style>
